define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mox/heritage/index' + location.search,
                    add_url: 'mox/heritage/add',
                    edit_url: 'mox/heritage/edit',
                    del_url: 'mox/heritage/del',
                    multi_url: 'mox/heritage/multi',
                    import_url: 'mox/heritage/import',
                    table: 'mox_heritage',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image },
                        {
                            field: 'video',
                            title: __('Video'),
                            operate: false,
                            formatter: function (value, row, index) {
                                if (!value) return '';

                                // 安全检查：防止XSS
                                value = Controller.api.safeVideoUrl(value);

                                // 视频格式识别
                                const ext = value.split('.').pop().toLowerCase();
                                const isVideo = ['mp4', 'webm', 'ogg'].includes(ext);

                                // 显示逻辑
                                if (isVideo) {
                                    return ` 
                                    <div class="video-cell">
                                    <i class="fa fa-film text-primary"></i>
                                    <a href="javascript:;" 
                                    class="video-preview" 
                                    data-url="${value}"
                                    data-title="${row.title || '视频预览'}">
                                    ${row.videofilename.filename}
                                    </a>
                                    ${row.video_thumb ? `<img src="${row.video_thumb}" class="video-thumb">` : ''}
                                    </div>
                                    `;
                                }
                                return `<a href="${value}" target="_blank">${row.videofilename.filename}</a>`;
                            },
                            events: {
                                'click .video-preview': function (e, value, row, index) {
                                    Controller.api.showVideoModal(value, row.title);
                                }
                            }
                        },
                        {
                            field: 'attachment',
                            title: __('附件'),
                            operate: false,
                            formatter: function (value, row, index) {
                                if (!value) return '<span class="text-muted">无附件</span>';

                                // 安全过滤
                                const safeUrl = value.replace(/[<>"']/g, '');
                                const filename = row.attachmentfilename.filename;
                                const ext = filename.split('.').pop().toLowerCase();

                                // 仅处理PDF文件
                                if (ext !== 'pdf') {
                                    return `<span class="text-danger">非PDF文件</span>`;
                                }

                                // PDF文件显示
                                return `
                                <div class="pdf-attachment">=
                                <i class="fa fa-file-pdf-o text-danger"></i>
                                <a href="${safeUrl}" 
                                target="_blank" 
                                class="pdf-download"
                                title="点击下载PDF"
                                download="${filename}">
                                ${filename}
                                </a>
                                ${row.pdf_thumb ? `<img src="${row.pdf_thumb}" class="pdf-thumbnail">` : ''}
                                 <button class="btn btn-xs btn-default pdf-preview" 
                                  data-url="${safeUrl}"
                                  title="在线预览">
                                  <i class="fa fa-eye"></i>
                                   </button>
                                   </div>
                                   `;
                            },
                            events: {
                                'click .pdf-preview': function (e, value, row, index) {
                                    // 使用PDF.js或第三方服务预览
                                    window.open(value, '_blank');
                                }
                            }
                        },
                        { field: 'admin.nickname', title: __('管理员') },
                        { field: 'user.nickname', title: __('关联用户') },
                        { field: 'create_time', title: __('Create_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        { field: 'update_time', title: __('Update_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            // 安全处理视频URL
            safeVideoUrl: function (url) {
                if (!url) return '';
                // 移除可能的恶意脚本
                return url.replace(/[\"\'<>]/g, '');
            },

            // 显示视频模态框
            showVideoModal: function (url, title) {
                const safeUrl = this.safeVideoUrl(url);
                const ext = safeUrl.split('.').pop().toLowerCase();
                const mimeTypes = {
                    mp4: 'video/mp4',
                    webm: 'video/webm',
                    ogg: 'video/ogg'
                };

                const modal = `
        <div class="modal fade" id="videoModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${title || '视频预览'}</h5>
                        <button type="button" class="close" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body text-center">
                        <video controls class="embed-responsive-item" style="width:100%">
                            <source src="${safeUrl}" type="${mimeTypes[ext] || 'video/mp4'}">
                            您的浏览器不支持HTML5视频
                        </video>
                    </div>
                    <div class="modal-footer">
                        <a href="${safeUrl}" class="btn btn-default" download>
                            <i class="fa fa-download"></i> 下载视频
                        </a>
                    </div>
                </div>
            </div>
        </div>`;

                $(modal).appendTo('body').modal('show')
                    .on('hidden.bs.modal', function () {
                        $(this).remove();
                    });
            }
        }
    };
    return Controller;
});